package com.lzw.blog.admin.service;

import com.lzw.blog.admin.pojo.User;

import com.lzw.blog.admin.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.UUID;

@Service
public class PasswordResetService {

    @Value("${spring.email.host}")
    String host;

    @Value("${spring.email.username}")
    String fromEmail;

    @Value("${spring.email.password}")
    String emailPassword;

    // Assume we have a UserRepository that can find users and save reset tokens

    @Autowired
    private UserService userService;
    public Result sendPasswordResetLink(String email) {
        // Find the user by email
        User user = userService.findUserByEmail(email);
        if (user != null) {
            // Generate a reset token and save it with the user's record
            String resetToken = UUID.randomUUID().toString();


            user.setResetToken(resetToken);
            userService.updateResetToken(user);

            // Create the reset link
            String resetLink = "http://localhost:8889/reset-password.html?token=" + resetToken;

            if (email == null || email.isEmpty()) {
                return Result.fail(400, "邮箱不能为空");
            }

            // 邮件主题
            String emailSubject = "密码重置";
            // 邮件内容
            String emailContent = "请点击以下链接来重置你的密码:\n" + resetLink;

            // 设置邮件服务器主机名
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.auth", "true");

            // 获取默认session对象
            Session mailSession = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, emailPassword); // 发件人邮箱账号、授权码
                }
            });

            try {
                // 创建默认的 MimeMessage 对象
                MimeMessage message = new MimeMessage(mailSession);

                // Set From: 头部头字段
                message.setFrom(new InternetAddress(fromEmail));

                // Set To: 头部头字段
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

                // Set Subject: 头部头字段
                message.setSubject(emailSubject);

                // 设置消息体
                message.setText(emailContent);

                // 发送消息
                Transport.send(message);
                System.out.println("Sent message successfully....");

                return Result.success("链接发送成功");

            } catch (MessagingException mex) {
                mex.printStackTrace();
                return Result.success("链接发送失败");
            }

        }
        return Result.success("链接发送失败");
    }

    public Result resetPassword(String token, String newPassword, String confirmPassword) {
        // 验证令牌的有效性
        // 检查新密码和确认密码是否匹配
        // 如果一切有效，更新用户密码

        // 假设我们有一个方法来验证令牌和更新密码

        User user = userService.findUserByResetToken(token);
        if (user == null) {
            return Result.fail(10000,"无效的重置令牌或令牌已过期。");
        }

        if (!newPassword.equals(confirmPassword)) {
            return Result.fail(10001,"新密码和确认密码不匹配。");
        }

        user.setPassword(newPassword);
        user.setResetToken(null);

        return userService.update(user);

    }
}
